// 处理数据库
const {
	dbQuery
} = require('../db/index');
const path = require('path');
// 处理验证
const joi = require('joi');
// 处理响应
const {
	sendError,
	sendSuccess
} = require('../tools/sendFunction.js');

// 设定验证规则
var guiZe = joi.object({
	title: joi.string().required().error(new Error('title不符合验证规则')),
	content: joi.string().required().allow('').error(new Error('content不符合验证规则')),
	state: joi.string().valid('草稿', '已发布').required().error(new Error('state不符合验证规则')),
	cate_id: joi.number().min(1).required().allow('').error(new Error('cate_id不符合验证规则'))
})

var guiZe2 = joi.object({
	pagenum: joi.number().required().min(1).error(new Error('pagenum不符合验证规则')),
	pagesize: joi.number().required().min(1).error(new Error('pagesize不符合验证规则')),
	state: joi.string().valid('草稿', '已发布', '').error(new Error('state不符合验证规则')),
	cate_id: joi.number().min(1).allow('').error(new Error('cate_id不符合验证规则'))
})

var guiZe3 = joi.object({
	id: joi.number().required().min(1).error(new Error('id不符合验证规则')),
})

var guiZe4 = joi.object({
	state: joi.string().valid('草稿', '已发布','').error(new Error('state不符合验证规则')),
	cate_id: joi.number().allow('').error(new Error('cate_id不符合验证规则'))
})


exports.getArticleTotal = async (req, res, next) => {
	let query = req.query;

	// 验证请求参数
	try {
		await guiZe4.validateAsync({
			cate_id: query.cate_id,
			state: query.state
		})
	} catch (error) {
		next(error)
		return
	}

	// 验证请求参数通过
	// 要查询的sql语句 和 值
	let sql = 'select count(*) from articles where is_delete!=1';
	let value = [];

	if (query.state && !query.cate_id) {
		sql = 'select count(*) from articles where state=? and is_delete!=1'
		value = [query.state]
	}

	if (query.cate_id && !query.state) {
		sql = 'select count(*) from articles where cate_id=? and is_delete!=1'
		value = [query.cate_id]
	}

	if (query.state && query.cate_id) {
		sql = 'select count(*) from articles where state=? and cate_id=? and is_delete!=1'
		value = [query.state, query.cate_id]
	}

	// 查询
	try {
		var result = await dbQuery(sql, value)
	} catch (error) {
		next(error);
		return;
	}

	sendSuccess(res, '获取文章数量成功!', {
		data: {
			count: result[0]['count(*)']
		}
	})
}

exports.addArticle = async (req, res, next) => {
	console.log(req.file);
	let {
		title,
		cate_id,
		content,
		state
	} = req.body;
	let id = req.user.id;

	if (req.file === undefined || req.file.fieldname !== 'cover_img') {
		next(new Error('file不符合验证规则'))
		return
	}

	// 验证请求参数
	try {
		await guiZe.validateAsync({
			title: title,
			cate_id: cate_id,
			content: content,
			state: state
		})
	} catch (error) {
		next(error)
		return
	}

	// 要插入数据库的数据
	const obj = {
		title: title,
		content: content,
		cover_img: path.join('/uploads', req.file.filename),
		pub_date: new Date(),
		state: state,
		cate_id: cate_id,
		author_id: id
	}

	// 插入
	try {
		var result = await dbQuery('insert into articles (title,content,cover_img,pub_date,state,cate_id,author_id) values (?,?,?,?,?,?,?)', [
			obj.title, obj.content, obj.cover_img, obj.pub_date, obj.state, obj.cate_id, obj.author_id
		])
	} catch (error) {
		next(error);
		return
	}

	// 插入失败
	if (result.affectedRows !== 1) {
		sendError(res, 200, '发布文章失败!');
	} else {
		// 插入成功
		sendSuccess(res, '发布文章成功!');
	}
}

exports.getArticleList = async (req, res, next) => {
	let body = req.query;

	// 验证请求参数
	try {
		await guiZe2.validateAsync({
			pagenum: body.pagenum,
			pagesize: body.pagesize,
			cate_id: body.cate_id,
			state: body.state
		})
	} catch (error) {
		next(error)
		return
	}

	// 请求参数验证通过
	// 处理页码问题
	let limit = (parseInt(body.pagenum) - 1) * parseInt(body.pagesize);
	if (body.pagenum == 1) {
		limit = 0;
	}

	let sql = 'select * from articles where is_delete!=1 limit ?,?';
	let value = [limit, parseInt(body.pagesize)];

	if (body.state && !body.cate_id) {
		sql = 'select * from articles where is_delete!=1 and state=? limit ?,? ';
		value = [body.state, limit, parseInt(body.pagesize)];
	}

	if (body.cate_id && !body.state) {
		sql = 'select * from articles where is_delete!=1 and  cate_id=? limit ?,? ';
		value = [body.cate_id, limit, parseInt(body.pagesize)];
	}

	if (body.state && body.cate_id) {
		sql = 'select * from articles where state=? and cate_id=? and is_delete!=1 limit ?,? ';
		value = [body.state, body.cate_id, limit, parseInt(body.pagesize)];
	}

	// 查询
	try {
		var result = await dbQuery(sql, value);
	} catch (error) {
		next(error);
		return;
	}

	if (result.length == 0) {
		sendError(res, 200, '获取文章列表数据失败,当前并无文章!')
	} else {
		for (var i = 0; i < result.length; i++) {
			try {
				var result2 = await dbQuery('select name from article_cate where id=?', result[i].cate_id);
				console.log(result2)
				result[i].cate_name = result2[0].name;
			} catch (error) {
				next(error);
				return;
			}
		}
		sendSuccess(res, '获取文章列表数据成功!', {
			data: result
		})
	}
}

exports.deleteArticleById = async (req, res, next) => {
	let id = req.params.id;

	// 验证请求参数
	try {
		await guiZe3.validateAsync({
			id: id
		})
	} catch (error) {
		next(error)
		return
	}

	// 请求参数验证通过
	// 更新
	try {
		var result = await dbQuery('update articles set is_delete=1 where id = ?', [id])
	} catch (error) {
		next(error);
		return
	}

	if (result.affectedRows !== 1) {
		sendError(res, 200, '删除文章失败!')
	} else {
		sendSuccess(res, '删除文章成功!')
	}
}

exports.getArticleById = async (req, res, next) => {
	let id = req.params.id;

	try {
		await guiZe3.validateAsync({
			id: id
		})
	} catch (error) {
		next(error)
		return
	}

	try {
		var result = await dbQuery('select * from articles where id=?', [id])
	} catch (error) {
		next(error);
		return
	}

	if (result.length !== 1) {
		sendError(res, 200, '获取文章数据失败!')
	} else {
		sendSuccess(res, '获取文章数据成功!', {
			data: result[0]
		})
	}
}

exports.updateArticle = async (req, res, next) => {
	
	let {
		title,
		cate_id,
		content,
		state,
		id
	} = req.body;

	if (req.file === undefined || req.file.fieldname !== 'cover_img') {
		next(new Error('file不符合验证规则'))
		return
	}

	try {
		await guiZe.validateAsync({
			title: title,
			cate_id: cate_id,
			content: content,
			state: state
		})
		await guiZe3.validateAsync({
			id: id
		})
	} catch (error) {
		next(error)
		return
	}

	// 要更新数据库的数据
	const obj = {
		title: title,
		content: content,
		cover_img: path.join('/uploads', req.file.filename),
		state: state,
		cate_id: cate_id,
	}

	try {
		var result = await dbQuery('update articles set title=?,content=?,cover_img=?,state=?,cate_id=? where id=?', [
			obj.title, obj.content, obj.cover_img, obj.state, obj.cate_id, req.body.id
		])
	} catch (error) {
		next(error)
		return
	}

	if (result.affectedRows !== 1) {
		sendError(res, 200, '更新文章失败!')
	} else {
		sendSuccess(res, '更新文章成功!')
	}
}